class Animal {
constructor(name = "Animal",lag = 4) {
this.name = name;
this.lag = lag;
}
run(lag) {
if(lag) {
this.lag = lag
}
console.log(`${this.name}用${this.lag}隻腳跑步!`)
}
stop() {
console.log(`${this.name}靜止不動!`)
}
}
let animal = new Animal("first animal")
接下來如果想要創建另外一個cat class,可以基於class animal做延伸,因為animal裡面的method都是可以套用在cat身上的:
class Cat extends Animal {
jump() {
console.log(`${this.name} hide!`)
}
}
let cat = new Cat("White cat")
cat.run(4); // White cat用4隻腳跑步!
假設在class Cat中有跟class Animal相同的函數,那cat會優先取用Cat.prototype中的方法:
class Cat extends Animal {
jump() {
console.log(`${this.name} hide!`)
}
stop() {
console.log(`${this.name}靜止跑步!`)
}
}
let cat = new Cat("White cat")
cat.stop(); // White cat靜止跑步!
如果要取用Animal的stop函數可以使用super(...):
class Cat extends Animal {
jump() {
console.log(`${this.name} hide!`)
}
stop() {
super.stop();
}
}
let cat = new Cat("White cat")
cat.stop(); // White cat靜止不動!
class Cat extends Animal {
jump() {
console.log(`${this.name} hide!`)
}
stop() {
setTimeout(() => super.stop(),1000)
}
}
let cat = new Cat("White cat")
cat.stop(); // White cat靜止不動!
如果是以function的形式則會報錯:
class Cat extends Animal {
jump() {
console.log(`${this.name} hide!`)
}
stop() {
setTimeout(function() {super.stop()},1000)
}
}
let cat = new Cat("White cat")
cat.stop(); // 'super' keyword unexpected here
上面例子中class Cat的constructor都是繼承class Animal的:
console.log(Cat.constructor===Animal.constructor)
如果直接新增constructor,以下寫法會報錯:
class Animal {
constructor(name = "Animal",lag = 4) {
this.name = name;
this.lag = lag;
}
run(lag) {
if(lag) {
this.lag = lag
}
console.log(`${this.name}用${this.lag}隻腳跑步!`)
}
stop() {
console.log(`${this.name}靜止不動!`)
}
}
class Cat extends Animal {
constructor(name = "Animal",lag = 4,color = white) {
this.name = name;
this.lag = lag;
this.color = color;
}
jump() {
console.log(`${this.name} hide!`)
}
}
let cat = new Cat(); // Must call super constructor in derived class before accessing 'this' or returning from derived constructor
extend的class如果要新增自己的constructor必須調用super,而且要在使用this之前:
class Animal {
constructor(name = "Animal",lag = 4) {
this.name = name;
this.lag = lag;
}
run(lag) {
if(lag) {
this.lag = lag
}
console.log(`${this.name}用${this.lag}隻腳跑步!`)
}
stop() {
console.log(`${this.name}靜止不動!`)
}
}
class Cat extends Animal {
constructor(name,lag,color = 'white') {
super(name,lag);
this.color = color;
}
jump() {
console.log(`${this.name} hide!`)
}
}
let cat = new Cat();
console.log(cat.color); // white